const express = require('express')
const router = express.Router()
const models = require('../db/models/index.js')
const baseUrl = '/todo_api'

//1.请求列表数据
router.post(baseUrl + '/list', async (req, res, next)=>{
	//测试状态500的异常
	//throw new Error('异常信息')
	try{
		//查询列表数据  currentPage-当前页 pageSize-每页显示记录数 offset-初始查询位置
		let { status, currentPage, pageSize } = req.body
		if(currentPage && pageSize){
			let offset = pageSize * (currentPage - 1);
			const result = await models.Todo.findAndCountAll()
			const list = await models.Todo.findAll({
				where: status ? {status} : {},
				offset,
				limit: pageSize,
			})
			res.json({
				code: 0,
				message: '查询成功',
				count: result.count,
				//和findAndCountAll查询结构保持一致
				data: {
					rows: list
				}
			})
		}else{
			res.json({
				code: 1001,
				message: '参数缺失',
				data: null
			})
		}
	}catch (err) {
		next(err)
	}
})

//2.添加列表数据
router.post(baseUrl + '/create', async (req, res, next)=>{
	try{
		let {name, deadline, content, status} = req.body//需使用bodyParser中间件才能获取数据
		//数据持久化到数据库
		let todo = await models.Todo.create({
			name,
			deadline,
			content,
			status,
		})
		res.json({
			code: 0,
			message: '任务创建成功',
			data: todo,
		})
	}catch (err){
		next(err)
	}
})

//3.更新列表数据
router.post(baseUrl + '/update', async (req, res, next)=>{
	try{
		let {name, deadline, content, id} = req.body
			models.Todo.update({
				name,
				deadline,
				content,
			},{
				where: {id}
			}).then(result => {
				res.json({
					message: '更新成功',
					code: 0,
				})
			}).catch(err => {
				res.json({
					message: err,
					code: 10001,
				})
			})
	}catch (err){
		next(err)
	}
})

//4.删除数据
router.post(baseUrl + '/delete', async (req, res, next)=>{
	try{
		let {id} = req.body
		//数据持久化到数据库
		let todo = await models.Todo.destroy({
			where: {
				id
			}
		})
		console.log(todo)
		if(todo){
			res.json({
				message: '操作成功',
				data: todo,
			})
		}else{
			res.json({
				message: '缺少参数id',
				data: null,
			})
		}
	}catch (err){
		next(err)
	}
})


module.exports = router